package com.bian.springboot04thymeleaf.controller;

import com.bian.springboot04thymeleaf.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author bianpengfei
 * @create 2019-01-31 15:09
 **/

@ControllerAdvice
public class MyExceptionHandler {
//    @ResponseBody
//    @ExceptionHandler(UserNotExistException.class)
//    public Map<String, Object> handlerException(Exception e) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("code", "user.notExist");
//        map.put("message", e.getMessage());
//        return map;
//    }


    @ExceptionHandler(UserNotExistException.class)
    public String handlerException(Exception e, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();

        // 传入我们自己错误的状态码  4xx 5xx
        //	Integer statusCode = (Integer) request
        //	    .getAttribute("javax.servlet.error.status_code");
        request.setAttribute("javax.servlet.error.status_code", 400);
        map.put("code", "user.notExist");
        map.put("message", e.getMessage());
        request.setAttribute("etc", map);
        return "forward:/error";
    }

}
